import Vue from 'vue'
import VueRouter from 'vue-router'

import Search from '@/views/search'
import SearchList from '@/views/search/list'
import ProDetail from '@/views/prodetail'
import Pay from '@/views/pay'
import MyOrder from '@/views/myorder'
import Login from '@/views/login'
import Layout from '@/views/layout'
import Home from '@/views/layout/home.vue'
import Cart from '@/views/layout/cart.vue'
import Category from '@/views/layout/category.vue'
import User from '@/views/layout/user.vue'

import userVuex from '@/store/modules/user'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login
    },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: Home
        },
        {
          path: '/cart',
          component: Cart// 需要认证
        },
        {
          path: '/category',
          component: Category
        },
        {
          path: '/user',
          component: User,
          meta: { requireAuth: true }
        }
      ]
    },
    {
      path: '/search',
      component: Search,
      meta: { requireAuth: true }
    },
    {
      path: '/searchlist',
      component: SearchList,
      meta: { requireAuth: true }
    },
    {
      path: '/prodetail/:id',
      component: ProDetail
    },
    {
      path: '/pay',
      component: Pay
    },
    {
      path: '/myorder',
      component: MyOrder
    }
  ]
})

router.beforeEach((to, from, next) => {
  const { token } = userVuex.state().userInfo // 获取token
  console.log('路由守卫经过咯,token=', token, 'to:', to.path, 'from', from.path)

  // 如果目标路由需要认证
  if (to.meta.requireAuth) {
    // 如果已登录，继续导航
    if (token) {
      next()
    } else {
      // 未登录，重定向到登录页
      next({ path: '/login' })
    }
  } else {
    next()
  }
})

export default router
